//
//  MerchantSearchView.m
//  TXSLiCai
//
//  Created by Owen on 16/8/3.
//  Copyright © 2016年 Arvin. All rights reserved.
//

#import "MerchantSearchView.h"
#import "MerchantHotSearchCell.h"
#import "FLMDropdownMenu.h"
#import "FLMMenuTableViewController.h"

NSInteger kDefaultHotCellColumn = 3;
CGFloat kDefaultHotCellCornerRadius = 5.0;

@interface MerchantSearchView()<UIScrollViewDelegate,UITextFieldDelegate,UICollectionViewDelegateFlowLayout,UITableViewDelegate,UITableViewDataSource,MerchantSearchHotCellDelegate,FLMDropdownMenuDelegate>

@property (nonatomic, strong) NSMutableArray   *modelArray;//存储数组
@property (nonatomic, strong) NSMutableArray   *searchArray;//搜索历史
@property (nonatomic, strong) UITableView      *tableView;
@property (nonatomic, copy)   Search search;
@property (nonatomic, strong) FLMDropdownMenu *menu;

@end

@implementation MerchantSearchView

#pragma mark - life cycle
- (instancetype)initSearchViewWithFrame:(CGRect)frame Parament:(id)parament search:(Search)search {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = UIColorFromRGB(0xf0eff5);
        [self prepareDataWithParament:parament];
        self.search = search;
        [self addSubview:self.searchTextFieldView];
        [self addSubview:self.tableView];
    }
    return self;
}

#pragma mark - 布局

#pragma mark - 赋值页面

#pragma mark - event response
- (void)textFieldCanceled:(UIButton *)btn {
    if([self.searchTextFieldView.delegate respondsToSelector:@selector(merchantSearchTextFieldViewDidCancel:)]) {
        [self.searchTextFieldView.delegate merchantSearchTextFieldViewDidCancel:self.searchTextFieldView];
    }
}

- (void)textFieldSourceChanged:(UIButton *)sender {
    FLMDropdownMenu *menu = [FLMDropdownMenu menuWithType:0];
    menu.titles = @[@"天猫",@"京东",@"淘宝"].mutableCopy;
    menu.delegate = self;
    [menu showFrom:sender];
}

- (void)dropdownMenuDidDismiss:(FLMDropdownMenu *)menu {
    NSString *title = [menu selectedTitle];
    if(title) {
        [self.searchTextFieldView.sourceButton setTitle:title forState:UIControlStateNormal];
    }
}

#pragma mark --点击空白回收键盘--
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self resignFirstResponderView:self];
}

- (void)resignFirstResponderView:(UIView *)view {
    NSArray *tempArray = view.subviews;
    if (tempArray.count < 1) {
        return;
    }
    else {
        for (UIView *aView in tempArray) {
            if ([aView isKindOfClass:[UITextField class]]) {
                UITextField *textField = (UITextField*)aView;
                
                [textField resignFirstResponder];
            }
            else if([aView isKindOfClass:[UITextView class]]) {
                UITextView *textView = (UITextView *)aView;
                
                [textView resignFirstResponder];
            }
            else {
                [self resignFirstResponderView:aView];
            }
        }
    }
}

#pragma mark - TableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *tempArray = [self.modelArray[section] objectForKey:@"section_content"];
    
    if(section == 0) return (tempArray.count - 1)/kDefaultHotCellColumn  + 1;
    
    return tempArray.count + 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.searchArray.count == 0) {
        return 1;
    }
    return self.modelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *tempArray = [self.modelArray[indexPath.section] objectForKey:@"section_content"];
    if(indexPath.section == 0) {
        MerchantHotSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MerchantHotSearchCell class]) forIndexPath:indexPath];
        cell.delegate = self;
        
        NSString *contenDic;
        for (NSInteger i = 0; i < kDefaultHotCellColumn; i++) {
            if (indexPath.row * kDefaultHotCellColumn + i > tempArray.count - 1) {
                break;
            }
            
            contenDic = tempArray[indexPath.row*kDefaultHotCellColumn + i];
            if(i == 0) {
                [cell.leftButton setTitle:contenDic forState:UIControlStateNormal];
            }
            else if(i == 1) {
                [cell.middleButton setTitle:contenDic forState:UIControlStateNormal];
            }
            else {
                [cell.rightButton setTitle:contenDic forState:UIControlStateNormal];
            }
        }
        
        return cell;
    }
    else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        NSDictionary *modelDic = self.modelArray[indexPath.section];
        NSArray *contenArray = modelDic[@"section_content"];
        
        if(indexPath.row == contenArray.count ) {
            cell.textLabel.frame = CGRectMake(0, 0, kScreenWidth, 40);
            cell.textLabel.text = @"清除搜索历史";
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            cell.textLabel.font = [UIFont systemFontOfSize:15.0];
            cell.textLabel.textColor = [UIColor lightGrayColor];
        }
        else {
            cell.textLabel.frame = CGRectMake(20, 0, kScreenWidth - 20, 40);
            cell.textLabel.textAlignment = NSTextAlignmentLeft;
            cell.textLabel.text = contenArray[indexPath.row];
            cell.textLabel.font = [UIFont systemFontOfSize:15.0];
            cell.textLabel.textColor = [UIColor lightGrayColor];
        }
        
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10.0;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell respondsToSelector:@selector(tintColor)]) {
        if (tableView == self.tableView) {
            CGFloat cornerRadius = kDefaultHotCellCornerRadius;
            
            cell.backgroundColor = UIColor.clearColor;
            
            CAShapeLayer *layer = [[CAShapeLayer alloc] init];
            CGMutablePathRef pathRef = CGPathCreateMutable();
            CGRect bounds = CGRectInset(cell.bounds, kMerchantSearchCellPadding, 0);
            
            BOOL addLine = NO;
            if (indexPath.row == 0 && indexPath.row == [tableView numberOfRowsInSection:indexPath.section] - 1) {
                CGPathAddRoundedRect(pathRef, nil, bounds, cornerRadius, cornerRadius);
            }
            else if (indexPath.row == 0) {
                
                CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
                
                CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMidX(bounds), CGRectGetMinY(bounds), cornerRadius);
                
                CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
                
                CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds));
                
                addLine = YES;
            }
            else if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
                CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
                
                CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
                
                CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
                
                CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
            }
            else {
                CGPathAddRect(pathRef, nil, bounds);
                addLine = YES;
            }
            
            layer.path = pathRef;
            
            CFRelease(pathRef);
            
            layer.fillColor = [UIColor colorWithWhite:1.f alpha:0.8f].CGColor;
            
            if (addLine == YES) {
                CALayer *lineLayer = [[CALayer alloc] init];
                
                CGFloat lineHeight = (1.f/[UIScreen mainScreen].scale);
                lineLayer.frame = CGRectMake(CGRectGetMinX(bounds), bounds.size.height-lineHeight, bounds.size.width, lineHeight);
                lineLayer.backgroundColor = tableView.separatorColor.CGColor;
                
                [layer addSublayer:lineLayer];
            }
            
            UIView *testView = [[UIView alloc] initWithFrame:bounds];
            [testView.layer insertSublayer:layer atIndex:0];
            testView.backgroundColor = UIColor.clearColor;
            
            cell.backgroundView = testView;
        }
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *tempArray = [self.modelArray[indexPath.section] objectForKey:@"section_content"];
    if(indexPath.section == 1 && indexPath.row == tempArray.count) {
        [self delectData:nil];
    }
}
#pragma mark - MerchantSearchHotCellDelegate
- (void)hotSearchCellButtonDidClicked:(UIButton *)sender
{
    NSString *text = sender.titleLabel.text;
    if(text) {
        self.searchTextFieldView.searchTextField.text = text;
        if (self.search) {
            self.search(text);
        }
    }
}
#pragma mark - headViewdelegate
- (void)delectData:(UIButton *)view {
    if(self.searchArray.count > 0) {
        [self.searchArray removeAllObjects];
        [[NSUserDefaults standardUserDefaults]setObject:nil forKey:MerchantSearch];
        [self.tableView reloadData];
    }
}
#pragma mark - scrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.searchTextFieldView.searchTextField resignFirstResponder];
}
#pragma mark - texteFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    if ([[textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] isEqualToString:@""]) {
        
        return NO;
    }
    if ([self.searchArray containsObject:textField.text]) {
        return YES;
    }
    [self.searchArray addObject:textField.text];
    [self.tableView reloadData];
    [[NSUserDefaults standardUserDefaults]setObject:self.searchArray forKey:MerchantSearch];
#warning mark - 添加搜索跳转
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([[textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] isEqualToString:@""]) {//如果没有文字处理
        
    }
    return YES;
}
#pragma mark - 数据请求

#pragma mark - 数据解析
- (void)prepareDataWithParament:(id)parament {
    NSDictionary *testDict = @{@"section_id":@"1",
                               @"section_title":@"热门搜索",
                               @"section_content":@[@"衣服",@"裤子",@"数据线",@"手机壳",@"男鞋",@"女鞋",@"袜子",@"风衣"]};
    [self.modelArray addObject:testDict];
    NSMutableDictionary *historyDic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"1",@"section_id",@"历史搜索",@"section_title", nil];
    NSArray *historyArray = [[NSUserDefaults standardUserDefaults] objectForKey:MerchantSearch];
    [self.searchArray addObjectsFromArray:historyArray];
    [historyDic setObject:self.searchArray forKey:@"section_content"];
    [self.modelArray addObject:historyDic];
}
#pragma mark - set get
- (NSMutableArray *)modelArray {
    if (_modelArray == nil) {
        _modelArray = [NSMutableArray array];
        
    }
    return _modelArray;
}
- (NSMutableArray *)searchArray {
    if (_searchArray == nil) {
        _searchArray = [NSMutableArray array];
    }
    return _searchArray;
}

- (UITableView *)tableView {
    if(!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 200*kHeightRatio, kScreenWidth, CGRectGetHeight(self.bounds) - 200*kHeightRatio) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = 0;
        _tableView.tableFooterView = [UIView new];
        [_tableView registerClass:[MerchantHotSearchCell class] forCellReuseIdentifier:NSStringFromClass([MerchantHotSearchCell class])];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
    }
    return _tableView;
}

- (MerchantSearchTextFieldView *)searchTextFieldView {
    if (_searchTextFieldView == nil) {
        _searchTextFieldView = [[MerchantSearchTextFieldView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 200*kHeightRatio)];
        _searchTextFieldView.searchTextField.delegate =self;
        [_searchTextFieldView.cancelButton addTarget:self action:@selector(textFieldCanceled:) forControlEvents:UIControlEventTouchUpInside];
         [_searchTextFieldView.sourceButton addTarget:self action:@selector(textFieldSourceChanged:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _searchTextFieldView;
}

@end
